from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.serializer.skus import GoodsCategorySerializer
from meiduo_admin.serializer.spu import SPUSerializer, BrandSerializer
from meiduo_admin.utils import UserPageNum

class SPUGoodView(ModelViewSet):

    # 指定查询集
    queryset = SPU.objects.all()
    # 指定序列化器
    serializer_class = SPUSerializer
    # 指定分页器
    pagination_class = UserPageNum
    # 权限
    permission_classes = [IsAdminUser]

    # 获取品牌信息
    def brand(self,request):
        spes = Brand.objects.all()
        ser = BrandSerializer(spes,many=True)
        return Response(ser.data)

    # 获取一级分类信息
    def channel(self,request):

        data = GoodsCategory.objects.filter(parent_id=None)
        ser = GoodsCategorySerializer(data,many=True)
        return Response(ser.data)
    #获取二级和三级分类数据
    def channels(self,request,pk):

        data = GoodsCategory.objects.filter(parent=pk)
        ser = GoodsCategorySerializer(data, many=True)
        return Response(ser.data)

    # 上传图片
    def  image(self,request):
        data = request.FILES.get('image')
        if data is None:
            return Response(status=500)
        # 2、建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        res = client.upload_by_buffer(data.read())
        if res['Status'] != 'Upload successed.':
            return  Response({'error': '上传失败'}, status=501)
        image_url = res['Remote file_id']
        return Response({
            'img_url':settings.FDFS_URL+image_url
        },status=201)















